package org.qhhc.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorTest {

    // 自定义对象
    static class Student {
        private String name;
        private int age;

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return name + " (" + age + ")";
        }
    }

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 18));
        students.add(new Student("Charlie", 22));

        // 示例1：使用匿名内部类按年龄升序排序 [2,4](@ref)
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return Integer.compare(s1.age, s2.age);
            }
        });
        System.out.println("按年龄升序：" + students);  // 输出：[Bob (18), Alice (20), Charlie (22)]

        // 示例2：使用Lambda表达式按姓名字典序排序 [4,5](@ref)
        students.sort((s1, s2) -> s1.name.compareTo(s2.name));
        System.out.println("按姓名排序：" + students);  // 输出：[Alice (20), Bob (18), Charlie (22)]

        // 示例3：链式排序（先按年龄降序，再按姓名排序）[4](@ref)
        Comparator<Student> compoundComparator = Comparator
                .comparingInt((Student s) -> s.age).reversed()
                .thenComparing(s -> s.name);
        students.sort(compoundComparator);
        System.out.println("复合排序：" + students);  // 输出：[Charlie (22), Alice (20), Bob (18)]
    }
}